<!--
  Copyright [2025] [OBARA (Nanjing) Electromechanical Co., Ltd]

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->


{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="小原焊枪选型数据库 - 专业的焊枪选型工具">
    <title>{% block title %}小原焊枪选型数据库{% endblock %}</title>
	{% load static %}
    <link rel="icon" type="image/x-icon" href="{% static 'icon/Obara_logo.bmp' %}">
	
    <!-- ✅ 推荐方式：使用 CDN1 引入（如使用请取消注释） 
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.3/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap-icons/1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
	-->

    <!-- 📁 使用本地资源 -->
    <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/bootstrap-icons.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/all.min.css' %}">
    
    <!-- PDF.js 库 -->
    <script src="{% static 'js/pdf.min.js' %}"></script>
    
    <style>
        :root {
            --primary-color: #0066cc;
            --secondary-color: #f8f9fa;
            --accent-color: #ff6b35;
            --text-dark: #2c3e50;
            --text-light: #6c757d;
            --border-color: #dee2e6;
            --shadow: 0 2px 10px rgba(0,0,0,0.1);
            --shadow-hover: 0 4px 20px rgba(0,0,0,0.15);
        }
        
        [data-bs-theme="dark"] {
            --primary-color: #4dabf7;
            --secondary-color: #212529;
            --accent-color: #fd7e14;
            --text-dark: #f8f9fa;
            --text-light: #adb5bd;
            --border-color: #495057;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: var(--text-dark);
            background-color: var(--secondary-color);
        }
        
        .navbar-brand {
            font-weight: 700;
            font-size: 1.5rem;
            color: var(--primary-color) !important;
        }
        
        .navbar {
            box-shadow: var(--shadow);
            background: rgba(255, 255, 255, 0.95) !important;
            backdrop-filter: blur(10px);
        }
        
        [data-bs-theme="dark"] .navbar {
            background: rgba(33, 37, 41, 0.95) !important;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, var(--primary-color), #0052a3);
            border: none;
            border-radius: 8px;
            padding: 12px 24px;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: var(--shadow);
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-hover);
            background: linear-gradient(135deg, #0052a3, var(--primary-color));
        }
        
        .btn-outline-primary {
            border: 2px solid var(--primary-color);
            color: var(--primary-color);
            border-radius: 8px;
            padding: 10px 20px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .btn-outline-primary:hover {
            background: var(--primary-color);
            transform: translateY(-1px);
            box-shadow: var(--shadow);
        }
        
        .card {
            border: none;
            border-radius: 12px;
            box-shadow: var(--shadow);
            transition: all 0.3s ease;
            background: white;
        }
        
        [data-bs-theme="dark"] .card {
            background: #2c3034;
        }
        
        .card:hover {
            transform: translateY(-4px);
            box-shadow: var(--shadow-hover);
        }
        
        .card-header {
            background: linear-gradient(135deg, var(--primary-color), #0052a3);
            color: white;
            border-radius: 12px 12px 0 0 !important;
            border: none;
            padding: 1.5rem;
            font-weight: 600;
        }
        
        .form-control, .form-select {
            border: 2px solid var(--border-color);
            border-radius: 8px;
            padding: 12px 16px;
            transition: all 0.3s ease;
            background: white;
        }
        
        [data-bs-theme="dark"] .form-control,
        [data-bs-theme="dark"] .form-select {
            background: #2c3034;
            border-color: var(--border-color);
            color: var(--text-dark);
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.2rem rgba(0, 102, 204, 0.25);
            transform: translateY(-1px);
        }
        
        .form-label {
            font-weight: 600;
            color: var(--text-dark);
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .table {
            border-radius: 12px;
            overflow: hidden;
            box-shadow: var(--shadow);
            background: white;
        }
        
        [data-bs-theme="dark"] .table {
            background: #2c3034;
        }
        
        .table thead th {
            background: linear-gradient(135deg, var(--primary-color), #0052a3);
            color: white;
            border: none;
            font-weight: 600;
            padding: 1rem;
        }
        
        .table tbody tr {
            transition: all 0.2s ease;
        }
        
        .table tbody tr:hover {
            background-color: rgba(0, 102, 204, 0.05);
            transform: scale(1.01);
        }
        
        .highlight-field {
            background: linear-gradient(135deg, #fff3cd, #ffeaa7);
            padding: 8px 12px;
            border-radius: 6px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            border: 2px solid transparent;
        }
        
        [data-bs-theme="dark"] .highlight-field {
            background: linear-gradient(135deg, #856404, #b08500);
            color: white;
        }
        
        .highlight-field:hover {
            background: linear-gradient(135deg, #ffeaa7, #fdcb6e);
            transform: scale(1.05);
            border-color: var(--accent-color);
        }
        
        .spinner-border {
            color: var(--primary-color);
        }
        
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.9);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            backdrop-filter: blur(5px);
        }
        
        [data-bs-theme="dark"] .loading-overlay {
            background: rgba(33, 37, 41, 0.9);
        }
        
        .alert {
            border: none;
            border-radius: 8px;
            padding: 1rem 1.5rem;
            margin-bottom: 1.5rem;
        }
        
        .alert-success {
            background: linear-gradient(135deg, #d4edda, #c3e6cb);
            color: #155724;
        }
        
        .alert-danger {
            background: linear-gradient(135deg, #f8d7da, #f5c6cb);
            color: #721c24;
        }
        
        .alert-warning {
            background: linear-gradient(135deg, #fff3cd, #ffeaa7);
            color: #856404;
        }
        
        .pagination .page-link {
            border: none;
            color: var(--primary-color);
            padding: 12px 16px;
            margin: 0 4px;
            border-radius: 8px;
            transition: all 0.3s ease;
        }
        
        .pagination .page-link:hover {
            background: var(--primary-color);
            color: white;
            transform: translateY(-2px);
            box-shadow: var(--shadow);
        }
        
        .pagination .page-item.active .page-link {
            background: var(--primary-color);
            border-color: var(--primary-color);
        }
        
        .badge {
            padding: 8px 12px;
            border-radius: 20px;
            font-weight: 600;
        }
        
        .theme-toggle {
            background: none;
            border: 2px solid var(--border-color);
            border-radius: 50%;
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
            color: var(--text-dark);
        }
        
        .theme-toggle:hover {
            border-color: var(--primary-color);
            color: var(--primary-color);
            transform: rotate(180deg);
        }

        .language-toggle {
            background: none;
            border: 2px solid var(--border-color);
            border-radius: 8px;
            padding: 8px 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
            color: var(--text-dark);
            text-decoration: none;
            font-weight: 600;
        }
        
        .language-toggle:hover {
            border-color: var(--primary-color);
            color: var(--primary-color);
            text-decoration: none;
        }
        
        .footer {
            background: linear-gradient(135deg, #2c3e50, #34495e);
            color: white;
            padding: 2rem 0;
            margin-top: 4rem;
        }
        
        .image-preview {
            max-width: 100px;
            max-height: 100px;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            border: 2px solid var(--border-color);
        }
        
        .image-preview:hover {
            transform: scale(1.1);
            border-color: var(--primary-color);
            box-shadow: var(--shadow);
        }
        
        .modal-content {
            border: none;
            border-radius: 12px;
            box-shadow: var(--shadow-hover);
        }
        
        .modal-header {
            background: linear-gradient(135deg, var(--primary-color), #0052a3);
            color: white;
            border-radius: 12px 12px 0 0;
            border: none;
        }
        
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .fade-in-up {
            animation: fadeInUp 0.6s ease-out;
        }
        
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
        
        .pulse {
            animation: pulse 2s infinite;
        }
        
        .search-form {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: var(--shadow);
            margin-bottom: 2rem;
        }
        
        [data-bs-theme="dark"] .search-form {
            background: #2c3034;
        }
        
        .results-header {
            background: linear-gradient(135deg, var(--primary-color), #0052a3);
            color: white;
            padding: 1.5rem;
            border-radius: 12px;
            margin-bottom: 1.5rem;
        }
        
        .product-card {
            transition: all 0.3s ease;
            border: 1px solid var(--border-color);
        }
        
        .product-card:hover {
            border-color: var(--primary-color);
            box-shadow: var(--shadow-hover);
        }

		.stats-card {
			background-color: #f8f9fa;
			color: #212529;
		}


		[data-bs-theme="dark"] .stats-card {
			background-color: #343a40;
			color: #f8f9fa;
		}

        /* 用户信息卡片样式 */
        .user-info-card {
            position: absolute;
            top: 100%;
            right: 0;
            width: 320px;
            background: white;
            border: none;
            border-radius: 12px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
            z-index: 1050;
            opacity: 0;
            visibility: hidden;
            transform: translateY(-10px);
            transition: all 0.3s ease;
            margin-top: 8px;
        }

        [data-bs-theme="dark"] .user-info-card {
            background: #2c3034;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
        }

        .user-info-card.show {
            opacity: 1;
            visibility: visible;
            transform: translateY(0);
        }

        .user-info-card .card-header {
            background: linear-gradient(135deg, var(--primary-color), #0052a3);
            color: white;
            border-radius: 12px 12px 0 0;
            padding: 1rem 1.25rem;
            font-weight: 600;
            font-size: 0.95rem;
            border: none;
        }

        .user-info-card .card-body {
            padding: 1.25rem;
        }

        .user-info-card .info-item {
            display: flex;
            align-items: center;
            margin-bottom: 0.75rem;
            font-size: 0.875rem;
            line-height: 1.4;
        }

        .user-info-card .info-item:last-child {
            margin-bottom: 0;
        }

        .user-info-card .info-item i {
            color: var(--primary-color);
            width: 16px;
            flex-shrink: 0;
        }

        .user-info-card .label {
            font-weight: 600;
            color: var(--text-dark);
            min-width: 90px;
            flex-shrink: 0;
        }

        .user-info-card .info-item span:last-child {
            color: var(--text-light);
            flex: 1;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .user-info-card {
                width: 280px;
                right: -20px;
            }
        }
    </style>
    
    {% block extra_css %}{% endblock %}
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-light fixed-top">
        <div class="container">
            <a class="navbar-brand" href="{% url 'clamps:home' %}">
                <i class="fas fa-industry me-2"></i>
                小原焊枪选型数据库
            </a>
            
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    {% if user.is_authenticated %}
                        <li class="nav-item">
                            <a class="nav-link" href="{% url 'clamps:search' %}">
                                <i class="bi bi-search text-success me-1"></i>产品搜索
                            </a>
                        </li>
                        {% if user.is_staff %}
                            <li class="nav-item">
                                <a class="nav-link" href="{% url 'clamps:management_dashboard' %}">
                                    <i class="bi bi-gear text-success me-1"></i>管理后台
                                </a>
                            </li>
                        {% endif %}
                    {% endif %}
                </ul>
                
                <ul class="navbar-nav">
                    <li class="nav-item" id="language-toggle-container">
                        <a href="javascript:void(0)" class="language-toggle me-3" onclick="switchLanguage()" title="Switch Language">
                            <i class="bi bi-translate me-1"></i>English
                        </a>
                    </li>
                    <li class="nav-item">
                        <button class="theme-toggle me-3" onclick="toggleTheme()" title="切换主题">
                            <i class="bi bi-sun-fill" id="theme-icon"></i>
                        </button>
                    </li>
                    {% if user.is_authenticated %}
                        <li class="nav-item position-relative">
                            <a class="nav-link" href="#" id="user-info-button">
                                <i class="bi bi-person-badge text-primary me-1"></i>{{ user.username }}
                            </a>
                            <!-- 用户信息卡片 -->
                            <div id="user-info-card" class="user-info-card">
                                <div class="card-header">
                                    <i class="bi bi-person-badge me-2"></i>个人信息
                                </div>
                                <div class="card-body">
									<div class="info-item">
										<i class="bi bi-shield-check me-2"></i>
										<span class="label">创建者：</span>
										<span id="created-by">加载中...</span>
									</div>
                                    <div class="info-item">
                                        <i class="bi bi-clock me-2"></i>
                                        <span class="label">密码过期时间：</span>
                                        <span id="password-expiry">加载中...</span>
                                    </div>
                                    <div class="info-item">
                                        <i class="bi bi-download me-2"></i>
                                        <span class="label">下载限制：</span>
                                        <span id="download-limit">加载中...</span>
                                    </div>
                                    <div class="info-item">
                                        <i class="bi bi-file-earmark me-2"></i>
                                        <span class="label">今日已下载：</span>
                                        <span id="daily-downloads">加载中...</span>
                                    </div>
                                    <div class="info-item">
                                        <i class="bi bi-hdd me-2"></i>
                                        <span class="label">今日下载大小：</span>
                                        <span id="daily-download-size">加载中...</span>
                                    </div>
                                </div>
                            </div>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="{% url 'clamps:logout' %}">
                                <i class="bi bi-box-arrow-in-right text-danger me-1"></i>退出登录
                            </a>
                        </li>
                    {% else %}
                        <li class="nav-item">
                            <a class="nav-link" href="{% url 'clamps:login' %}">
                                <i class="bi bi-box-arrow-in-right text-success me-1"></i>登录
                            </a>
                        </li>
                    {% endif %}
                </ul>
            </div>
        </div>
    </nav>
    
    <!-- 主要内容 -->
    <main style="margin-top: 80px; min-height: calc(100vh - 160px);">
        <div class="container">
            <!-- 消息提示 -->
            {% if messages %}
                {% for message in messages %}
                    <div class="alert alert-dismissible fade show fade-in-up" role="alert" style="background-color: #e0f7fa; border: 1px solid #b2ebf2; border-radius: 8px; color: #2c3e50; padding: 12px 16px; margin-bottom: 16px;">
                        <i class="bi bi-info-circle me-2" style="color: #2c3e50;"></i>
                        {{ message }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert" style="color: #2c3e50; opacity: 0.7;"></button>
                    </div>
                {% endfor %}
            {% endif %}
            
            {% block content %}{% endblock %}
        </div>
    </main>
    
    <!-- 页脚 -->
    <footer class="footer">
        <div class="container">
            <div class="row">
                <div class="col-md-6">
                    <h5><i class="fas fa-industry me-2"></i>小原（南京）机电有限公司</h5>
                    <p class="mb-1">
                        <i class="bi bi-geo-alt me-2"></i>
                        中国·南京市江宁区仁杰路28号
                    </p>
                    <p class="mb-1">
                        <i class="bi bi-card-text me-2"></i>
                        备案号：苏ICP备05020192号-1
                    </p>
                    <p class="mb-0">
                        <i class="bi bi-envelope me-2"></i>
                        技术部门邮箱：gaoj@obara.com.cn
                    </p>
                </div>
                <div class="col-md-6 text-md-end">
                    <p class="mb-1">以客户为中心 关怀员工 鼓励创新 纳新去旧</p>
                    <p class="mb-1"><small>Be customer-oriented care employees encourage innovations take in the fresh</small></p>
                    <p class="mb-1">版权所有 © <span id="current-year">1994</span>-<span id="current-year-end"></span> 小原（南京）机电有限公司</p>
					<p class="mb-0" id="release-version">正在获取最新版本...</p>
                </div>
            </div>
        </div>
    </footer>
    
    <!-- Bootstrap JS -->
	<!-- ✅ 推荐方式：使用 CDN1 引入（如使用请取消注释） 
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
	-->
	
	 <!-- 📁 使用本地资源 -->
    <script src="{% static 'js/bootstrap.bundle.min.js' %}"></script>
    
    <script>
        // 主题切换功能
        function toggleTheme() {
            const html = document.documentElement;
            const themeIcon = document.getElementById('theme-icon');
            
            if (html.getAttribute('data-bs-theme') === 'dark') {
                html.setAttribute('data-bs-theme', 'light');
                themeIcon.className = 'bi bi-sun-fill';
                localStorage.setItem('theme', 'light');
            } else {
                html.setAttribute('data-bs-theme', 'dark');
                themeIcon.className = 'bi bi-moon-fill';
                localStorage.setItem('theme', 'dark');
            }
        }
        
        /// **修正后的语言切换功能**
    function switchLanguage() {
        const currentPath = window.location.pathname;
        let newPath = currentPath;

        // 定义中英文页面的URL映射关系
        const translatablePaths = [
            { zh: "/", en: "/_en/" },
            { zh: "/login/", en: "/login_en/" },
            { zh: "/search/", en: "/search_en/" },
            { zh: "/search/results/", en: "/search/results_en/" },
            // 使用正则表达式处理产品详情页
            { zh: /^\/product\/(\d+)\/$/, en: "/product/$1_en/" },
            { en: /^\/product\/(\d+)_en\/$/, zh: "/product/$1/" }
        ];

        // 判断当前是在中文页还是英文页
        const isEnglishPage = currentPath.includes('_en/') || translatablePaths.some(p => p.en instanceof RegExp && p.en.test(currentPath));

        if (isEnglishPage) {
            // 当前是英文页，目标是切换到中文
            for (const pathMap of translatablePaths) {
                if (typeof pathMap.en === 'string' && currentPath === pathMap.en) {
                    newPath = pathMap.zh;
                    break;
                } else if (pathMap.en instanceof RegExp && pathMap.en.test(currentPath)) {
                    newPath = currentPath.replace(pathMap.en, pathMap.zh);
                    break;
                }
            }
        } else {
            // 当前是中文页，目标是切换到英文
            for (const pathMap of translatablePaths) {
                if (typeof pathMap.zh === 'string' && currentPath === pathMap.zh) {
                    newPath = pathMap.en;
                    break;
                } else if (pathMap.zh instanceof RegExp && pathMap.zh.test(currentPath)) {
                    newPath = currentPath.replace(pathMap.zh, pathMap.en);
                    break;
                }
            }
        }

        // 如果路径发生变化，则跳转
        if (newPath !== currentPath) {
            // 保留查询参数
            window.location.href = newPath + window.location.search;
        }
    }

    // 初始化主题和语言状态 (大部分保持不变，仅微调)
    document.addEventListener("DOMContentLoaded", function() {
        // 主题初始化
        const savedTheme = localStorage.getItem('theme') || 'light';
        document.documentElement.setAttribute('data-bs-theme', savedTheme);
        document.getElementById('theme-icon').className = savedTheme === 'dark' ? 'bi bi-moon-fill' : 'bi bi-sun-fill';

        // 语言切换按钮文本初始化
        const languageToggleBtn = document.querySelector(".language-toggle");
        const currentPath = window.location.pathname;
        const isEnglishPage = currentPath.includes('_en/');
        
        if (languageToggleBtn) {
            if (isEnglishPage) {
                languageToggleBtn.innerHTML = "<i class=\"bi bi-translate me-1\"></i>中文";
            } else {
                languageToggleBtn.innerHTML = "<i class=\"bi bi-translate me-1\"></i>English";
            }
        }
    });
        
        // 加载动画
        function showLoading() {
            const loadingHtml = `
                <div class="loading-overlay">
                    <div class="text-center">
                        <div class="spinner-border mb-3" role="status" style="width: 3rem; height: 3rem;">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <div>正在处理您的请求...</div>
                    </div>
                </div>
            `;
            document.body.insertAdjacentHTML('beforeend', loadingHtml);
        }
        
        function hideLoading() {
            const loading = document.querySelector('.loading-overlay');
            if (loading) {
                loading.remove();
            }
        }
        
        // 图片预览功能
        function previewImage(src, title) {
            const modal = new bootstrap.Modal(document.getElementById('imageModal') || createImageModal());
            document.getElementById('modalImage').src = src;
            document.getElementById('modalTitle').textContent = title || '图片预览';
            modal.show();
        }
        
        function createImageModal() {
            const modalHtml = `
                <div class="modal fade" id="imageModal" tabindex="-1">
                    <div class="modal-dialog modal-lg modal-dialog-centered">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="modalTitle">图片预览</h5>
                                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body text-center">
                                <img id="modalImage" class="img-fluid" style="max-height: 70vh;">
                            </div>
                        </div>
                    </div>
                </div>
            `;
            document.body.insertAdjacentHTML('beforeend', modalHtml);
            return document.getElementById('imageModal');
        }
        
        // 表单提交时显示加载动画
        document.addEventListener('DOMContentLoaded', function() {
            const forms = document.querySelectorAll('form');
            forms.forEach(form => {
                form.addEventListener('submit', function() {
                    showLoading();
                });
            });
        });
		
		// 自动获取当前年份
		const currentYear = new Date().getFullYear();
		document.getElementById('current-year-end').textContent = currentYear;
		
		// 自动获取项目 https://gitee.com/caifugao110/servogun2 的最新发行版标签
		document.addEventListener("DOMContentLoaded", function() {
			const owner = 'caifugao110';
			const repo = 'servogun2';
			const apiUrl = `/api/gitee/releases/latest/${owner}/${repo}/`;
			const versionElement = document.getElementById('release-version');
			const CACHE_KEY = 'latest_release_version';
			const CACHE_EXPIRE = 3600000; // 1小时（毫秒）

			// 检查缓存
			const cachedData = localStorage.getItem(CACHE_KEY);
			if (cachedData) {
				const { version, timestamp } = JSON.parse(cachedData);
				if (Date.now() - timestamp < CACHE_EXPIRE) {
					versionElement.textContent = `Released and deployed as version ${version}`;
					return; // 直接使用缓存，不发起请求
				}
			}

			// 缓存过期，发起请求（带超时控制）
			const timeoutPromise = new Promise((_, reject) => {
				setTimeout(() => reject(new Error('请求超时')), 5000);
			});

			Promise.race([fetch(apiUrl), timeoutPromise])
				.then(response => response.ok ? response.json() : Promise.reject())
				.then(data => {
					if (data?.tag_name) {
						// 存入缓存
						localStorage.setItem(CACHE_KEY, JSON.stringify({
							version: data.tag_name,
							timestamp: Date.now()
						}));
						versionElement.textContent = `Released and deployed as version ${data.tag_name}`;
					}
				})
				.catch(error => {
					console.error('获取版本失败:', error);
					versionElement.textContent = '获取版本失败';
				});
		});

        // 用户信息卡片功能
        document.addEventListener("DOMContentLoaded", function() {
            const userInfoButton = document.getElementById('user-info-button');
            const userInfoCard = document.getElementById('user-info-card');
            let userProfileData = null;

            if (userInfoButton && userInfoCard) {
                // 鼠标悬停显示卡片
                userInfoButton.addEventListener('mouseenter', function(event) {
                    event.preventDefault(); // 阻止默认跳转行为
                    // 每次悬停都重新获取最新数据
                    fetchUserProfileData();
                    userInfoCard.classList.add('show');
                });

                // 鼠标离开按钮时延迟隐藏卡片
                userInfoButton.addEventListener('mouseleave', function(event) {
                    setTimeout(function() {
                        if (!userInfoCard.matches(':hover') && !userInfoButton.matches(':hover')) {
                            userInfoCard.classList.remove('show');
                        }
                    }, 100);
                });

                // 鼠标进入卡片时保持显示
                userInfoCard.addEventListener('mouseenter', function(event) {
                    userInfoCard.classList.add('show');
                });

                // 鼠标离开卡片时隐藏
                userInfoCard.addEventListener('mouseleave', function(event) {
                    userInfoCard.classList.remove('show');
                });

                // 定义获取用户数据的函数
                function fetchUserProfileData() {
                    fetch('/api/user_profile_data/?days=1')
                        .then(response => response.json())
                        .then(data => {
                            userProfileData = data;
                            updateUserInfoCard(data);
                        })
                        .catch(error => {
                            console.error('获取用户信息失败:', error);
                            updateUserInfoCard({
                                created_by: "获取失败",
                                password_expiry_date: "获取失败",
                                max_daily_download_gb: "N/A",
                                max_daily_download_count: "N/A",
                                daily_download_count: "N/A",
                                daily_download_size_mb: "N/A"
                            });
                        });
                }

                // 初始化时获取一次数据（可选，因为现在每次悬停都会获取）
                fetchUserProfileData();
            }

            // 更新用户信息卡片内容
            function updateUserInfoCard(data) {
                document.getElementById('created-by').textContent = data.created_by || "N/A";
                
                // 处理密码过期时间，如果是永久有效则显示相应文本
                let passwordExpiryText = data.password_expiry_date || "N/A";
                if (passwordExpiryText === "永久有效" || passwordExpiryText === "Permanent") {
                    passwordExpiryText = "永久有效";
                }
                document.getElementById('password-expiry').textContent = passwordExpiryText;
                
                document.getElementById('download-limit').textContent = `${data.max_daily_download_gb}GB/${data.max_daily_download_count}个/天`;
                document.getElementById('daily-downloads').textContent = `${data.daily_download_count}个`;
                document.getElementById('daily-download-size').textContent = `${(data.daily_download_size_mb / 1024).toFixed(2)}GB`;
            }
        });
    </script>
    
    {% block extra_js %}{% endblock %}
</body>
</html>

